package com.service.atm;

import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import oracle.sql.CLOB;

import com.bpms.common.Base64;
import com.bpms.common.CommonUtil;
import com.bpms.common.Constant;
import com.bpms.common.DBOperation;
import com.bpms.common.HttpUtil;
import com.bpms.common.JdbcWorker;
import com.bpms.common.Param;
import com.bpms.common.VO;
import com.bpms.esb.IService;
import com.bpms.esb.SV;
import com.service.util.BillPhoto;

/**
 * 1001 接收支票影像 返回报文
 * 
 * @author Menlin
 * 
 */
public class Answer_atm_check_image implements IService {

	private long INSTANCEID;
	private String bizid;

	// private JdbcWorker jdbcWorker;
	public VO exec(VO args) {
		CommonUtil.debug("Answer_atm_check_image begin");
		try {
			// jdbcWorker = new JdbcWorker();
			INSTANCEID = getBizid(); // 支票序列号
			bizid = new SimpleDateFormat("yyMMddHHmmss").format(new Date())
					+ String.format("%08d", INSTANCEID);
			// 验证二维码预留 张锐接口
			// 苏州中行逻辑
			Map<String, String> checkMark = checkQuickMark(args.getAttr("IMGDATA"));
			boolean ispass = (checkMark != null);
			args.setAttr("CHECKMARKRESULT", ispass ? "Y" : "N"); // 二维码验证结果
			args.setAttr("DRAWEEACCNO", ispass ? checkMark.get("DRAWEEACCNO")
					: ""); // 付款人账号(开户人账号)
			args.setAttr("PINGZHENGHAO", ispass ? checkMark.get("PINGZHENGHAO")
					: "");// 凭证号
			args.setAttr("EXCHANGEBANKNO", ispass ? checkMark
					.get("EXCHANGEBANKNO") : ""); // 交换行号
			
			// 包商银行逻辑
//			boolean ispass = true;
//			args.setAttr("CHECKMARKRESULT", ispass ? "Y" : "N"); // 二维码验证结果
//			args.setAttr("DRAWEEACCNO", ispass ? ""
//					: ""); // 付款人账号(开户人账号)
//			args.setAttr("PINGZHENGHAO", ispass ? ""
//					: "");// 凭证号
//			args.setAttr("EXCHANGEBANKNO", ispass ? "" : ""); // 交换行号
			
			
			// 保存影像
			List<String> photoPathList = saveImage(args);
			// 插入数据库
			this.saveLocal(photoPathList, args);
			// 返回报文结果
			VO result = this.packResult(args, ispass);
			return result;
		} catch (Exception e) {
			CommonUtil.error("Answer_atm_check_image  error exception::", e);
			return this.failResult(args);
		}
	}

	/**
	 * 验证二维码<br>
	 * 返回空校验二维码失败，成功返回凭证号、付款人账号、开户行交换行号
	 * 
	 * @param IMGDATA
	 * @return Map
	 * @throws Exception
	 */
	private Map<String, String> checkQuickMark(String IMGDATA) {
		String url = Param.getValue("ATMP", "atmp_chequesellpart_path");
		// String url = "http://22.202.31.62:8080/EWM/checkEWM.do";
		Map<String, String> map = new HashMap<String, String>();
		map.put("data", IMGDATA);
		Map<String, String> r = null;
		try {
			String result = HttpUtil.postRequest(url, map);
			if ("0000".equals(result)) {
				return null;
			}
			JSONObject jret = new JSONObject(result);
			JSONArray ja = jret.optJSONArray("list");
			JSONObject jo = ja.optJSONObject(0);
			r = new HashMap<String, String>();
			r.put("DRAWEEACCNO", jo.optString("ACCOUNT")); // 付款人账号(开户人账号)
			r.put("PINGZHENGHAO", jo.optString("CERTNUM")); // 凭证号
			r.put("EXCHANGEBANKNO", jo.optString("BANKID")); // 交换行号
		} catch (Exception e) {
			CommonUtil.error("连接二维码校验接口异常：", e);
		}
		return r;
	}

	/**
	 * 保存到数据库
	 */
	private VO saveLocal(List<String> photoPathList, VO args) {
		String front_billPath = photoPathList.get(0);
		String back_billPath = photoPathList.get(1);
		args.setAttr("front_checkPath", front_billPath);
		args.setAttr("back_checkPath", back_billPath);
		args.setAttr("BIZID", bizid);
		args.setAttr("INSTANCEID", INSTANCEID + "");
		args.setAttr("FLAG", Constant.CM_DJB_FLAG_TMP);
		VO result = SV.g("atm.Savedealinfo", args);
		return result;
	}

	/**
	 * 保存影像,并返回影像保存路径集合
	 * 
	 * @param vo
	 * @return List
	 * @throws Exception
	 */
	private List<String> saveImage(VO vo) throws Exception {
		String path = Param.getValue("UAI", "bill_photo_save_path");
		List<String> list = new ArrayList<String>();
		if (path != null) {
			int count = Integer.parseInt(vo.getAttr("IMGNUM"));
			path += new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/"; // 按照日期保存
			String filename = vo.getAttr("DEVICENO") + "-" + bizid + "-"
					+ vo.getAttr("NETNUM") + "-" + vo.getAttr("BILLTYPE")
					+ "-1001";
			if (count > 0) {
				for (int i = 0; i < count; i++) {
					byte[] photo = Base64.decode(vo.getAttr("photo" + (i + 1)));
					String photo1name = filename + "-" + i + ".jpg";
					list.add(path + photo1name);
					BillPhoto.save(path, photo1name, photo);
				}
			}
		} else {
			CommonUtil.debug("image path is null--影像保存路径为空");
		}
		return list;
	}

	/**
	 * 生成报文
	 * 
	 * @param args
	 * @param ispass 二维码校验是否通过
	 * @return VO
	 * @throws UnsupportedEncodingException
	 */
	private VO packResult(VO arg, boolean ispass) throws Exception {
		VO vo = new VO();
		StringBuffer message = new StringBuffer(50);
		message.append("00000000"); // 流水号
		message.append("00000000"); // 报文体长度
		message.append("1001"); // 交易码 u_char[4]
		message.append("0000"); // 应答结果 u_char[4]
		// String billno = arg.getAttr("BILLNO"); // 票据号码
		String pingzhenghao = arg.getAttr("PINGZHENGHAO"); // 凭证号
		String EXCHANGEBANKNO = arg.getAttr("EXCHANGEBANKNO"); // 开户行交换行号
		String DRAWEEACCNO = arg.getAttr("DRAWEEACCNO"); // 开户人账号
		String systemtype = arg.getAttr("SYSTEMTYPE"); // 对应集中处理系统的业务类型
		// String idcard = arg.getAttr("IDCARD"); // 开户人账号（身份证号？）
		String imgdata = arg.getAttr("IMGDATA"); // 二维码
		String msg = ispass ? "success" : "二维码校验未通过";
		message.append(ispass ? "00000004R0010000" : "00000004R0019999"); // 处理结果代码
		message.append(String.format("%08d", msg.getBytes("gb2312").length)
				+ "R002" + msg); // 结果描述
		message.append("00000020R003" + bizid); // 业务流水号
		// 返回票据号码
		// message.append(String.format("%08d",
		// billno.getBytes("gb2312").length) + "R004" + billno); // 票据号码
		// 凭证号
		message.append(String.format("%08d",
				pingzhenghao.getBytes("gb2312").length)
				+ "R004" + pingzhenghao);
		// 返回付款人账号
		message.append(String.format("%08d", DRAWEEACCNO.getBytes("gb2312").length)
				+ "R005" + DRAWEEACCNO);
		// 开户行交换行号
		message.append(String.format("%08d",
				EXCHANGEBANKNO.getBytes("gb2312").length)
				+ "R006" + EXCHANGEBANKNO);
		// 对应集中处理系统的业务类型
		message.append(String.format("%08d",
				systemtype.getBytes("gb2312").length)
				+ "R007" + systemtype);
		int bodyLen = message.toString().getBytes("gb2312").length;
		// 报文体长度
		message.replace(8, 16, String.format("%08d", bodyLen - 24));
		// 报文长度
		message.insert(0, String.format("%08d", bodyLen));
		CommonUtil.debug("成功返回报文：" + message.toString());
		vo.setAttr("msg", message.toString());
		return vo;
	}

	/**
	 * 失败或发生异常情况返回报文
	 * 
	 * @param arg
	 * @return
	 */
	private VO failResult(VO arg) {
		VO vo = new VO();
		StringBuilder message = new StringBuilder(50);
		message.append("00000000"); // 流水号
		message.append("00000000"); // 报文体长度
		message.append("1001"); // 交易码 u_char[4]
		message.append("0000"); // 应答结果 u_char[4]
		String exception = "exception";
		message.append("00000004R0019999"); // 处理结果代码
		message.append("00000009R002" + exception);
		message.append("00000020R003" + bizid); // 业务流水号
		// 凭证号
		message.append("00000000R004");
		// 返回付款人账号
		message.append("00000000R005");
		// 开户行交换行号
		message.append("00000000R006");
		// 对应集中处理系统的业务类型
		message.append("00000000R007");
		int bodyLen = message.length();
		// 报文体长度
		message.replace(8, 16, String.format("%08d", bodyLen - 24));
		// 报文长度
		message.insert(0, String.format("%08d", bodyLen));
		vo.setAttr("msg", message.toString());
		CommonUtil.debug("异常或者失败返回报文：" + message.toString());
		return vo;
	}

	private long getBizid() throws Exception {
		JdbcWorker j = new JdbcWorker();
		long INSTANCEID = j.getSeqValue("cmdjb_bizid");
		return INSTANCEID;
	}

	/**
	 * 持久化数据以备转发集中作业管理中心
	 * 
	 * @param data
	 * @throws Exception
	 * 
	 * private void localize(VO arg) throws Exception { String data =
	 * arg.getAttr("data"); if (data != null) { // 生成ID String id = new
	 * Date().getTime() + arg.getAttr("DEVICENO"); // 插入一条记录 StringBuffer
	 * insert_sql = new StringBuffer(100); insert_sql.append("INSERT INTO
	 * atmp_tempdata(id,bizid,data,flag,type) VALUES
	 * ('"+id+"','"+bizid+"',empty_clob(),'0','1001')");
	 * jdbcWorker.execute(insert_sql.toString()); // 更改新增记录的clob字段值 StringBuffer
	 * update_sql = new StringBuffer(100); update_sql.append("SELECT data FROM
	 * atmp_tempdata WHERE id='"+id+"' for update"); DBOperation db = null;
	 * Connection conn = null; ResultSet rs = null; try { db = new
	 * DBOperation(); conn = db.getCon(); rs = db.getrs(update_sql.toString());
	 * CLOB clob = null; if (rs.next()) { clob = (CLOB) rs.getClob(1); }
	 * @SuppressWarnings("deprecation") Writer writer =
	 *                                  clob.getCharacterOutputStream();
	 *                                  writer.write(data); writer.flush();
	 *                                  writer.close(); } finally { rs.close();
	 *                                  conn.commit(); db.closed(); db = null; } }
	 *                                  else { CommonUtil.debug("data数据为空"); } }
	 */
}
